package edu.spbu.eclipse.adressbook.zhukovazalog;
/**
 * 
 * @author Anna Zhukova
 * @author Leonid Zalog
 *
 */

import java.util.*;
import java.io.*;

public class Model extends Observable {
	public void loadFromFile() throws IOException {
		{
			BufferedReader inputStream;
			inputStream = new BufferedReader(new FileReader("LAOutput.txt"));
			XMLBuilder First = new XMLBuilder();
			String MaybeTag;
			while (true) {
				String str = null;
				str = inputStream.readLine();
				if (str == null)
					break;
				StringTokenizer tokenizer = new StringTokenizer(str, " \n'[]");
				while (tokenizer.hasMoreTokens()) {
					MaybeTag = tokenizer.nextToken();
					MaybeTag.trim();
					if (MaybeTag.charAt(0) == '<') {
						if (MaybeTag.charAt(1) == '/') {
							if (MaybeTag.charAt(MaybeTag.length() - 1) == '>') {
								First.TagClosed((MaybeTag));
							}
						} else {
							if (MaybeTag.charAt(MaybeTag.length() - 1) == '>') {
								First.TagOpened(MaybeTag);
							}
						}
					} else {
						First.Text(MaybeTag, First.getStatement());
					}
				}
			}
			First.endOfFile();
		}
	}

	/**
	 * This method saves info ti the file
	 * 
	 * @param rowToSave
	 * @throws IOException
	 */

	public void saveToFile(Vector rowToSave) throws IOException {
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
				("LAOutput.txt"))));
		Iterator j = rowToSave.listIterator();
		while (j.hasNext()) {
			Vector v = (Vector) j.next();
			String saveName = (String) ((LinkedList) v.get(0)).get(0);
			String saveLastName = (String) ((LinkedList) v.get(1)).get(0);
			LinkedList saveMobileNumber = (LinkedList) v.get(2);
			LinkedList saveHomeNumber = (LinkedList) v.get(3);
			LinkedList saveEmail = (LinkedList) v.get(4);
			out.write(" <name> " + saveName + " </name> ");
			out.write(" <lastName> " + saveLastName + " </lastName> ");
			Iterator i;
			i = saveMobileNumber.listIterator();
			while (i.hasNext()) {
				out.write(" <mobileNumber> " + (String) i.next()
						+ " </mobileNumber> ");
			}
			i = saveHomeNumber.listIterator();
			while (i.hasNext()) {
				out.write(" <homeNumber> " + (String) i.next()
						+ " </homeNumber> ");
			}
			i = saveEmail.listIterator();
			while (i.hasNext()) {
				out.write(" <email> " + (String) i.next() + " </emailNumber> ");
			}
		}
		out.close();
	}
}
